package com.xiangyueEducation.uploaderCloud.utils;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CaptchaUtil {
    // 用于存储验证码的内存缓存
    private final ConcurrentHashMap<String, String> captchaStore = new ConcurrentHashMap<>();

    // 创建定时任务池
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    // 生成验证码并存储到内存
    public String generateCaptcha(String username) {
        // 生成一个 6 位数的验证码
        String captcha = String.format("%06d", new Random().nextInt(1000000));
        //截取前四位
        String finalCaptcha = captcha.substring(0,4);

        // 将验证码存储到内存中
        captchaStore.put(username, finalCaptcha);

        // 设置 5 分钟后删除验证码
        scheduler.schedule(() -> {
            captchaStore.remove(username);
            log.info("验证码已过期并已删除: " + finalCaptcha);
        }, 5, TimeUnit.MINUTES);

        // 返回生成的验证码
        return finalCaptcha;
    }

    // 获取验证码
    public String getCaptcha(String username) {
        return captchaStore.get(username);
    }

    public boolean isCaptchaValid(String username){
        return getCaptcha(username)!=null;
    }

    public boolean verifyCaptcha(String username, String captcha) {
        //验证
        boolean res = getCaptcha(username).equals(captcha);
        //善后处理
        if (res) captchaStore.remove(username);

        return res;
    }





}


